import axios from 'axios';
import { Notification } from 'element-ui';

// 创建 axios 实例
const service = axios.create({
    // API 请求的默认前缀
    baseURL: process.env.VUE_APP_API_BASE_URL,
    // 请求超时时间
    timeout: 6000,
    // 允许携带cookie
    withCredentials: false
});

// 异常拦截处理器
const errorHandler = (error) => {
    if (error.response) {
        Notification({
            title: '提示',
            message: error.response.message || 'Error',
            type: 'error',
            duration: 3000
        });
    }
    return Promise.reject(error);
};

// 请求拦截
service.interceptors.request.use(config => {
    const token = localStorage.getItem('ACCESS_TOKEN');

    // 如果 token 存在 让每个请求携带token
    if (token) {
        config.headers['Authorization'] = `Bearer ${token}`;
    }
    // post请求在请求地址拼接时间戳
    if (config.method === 'post') {
        config.params = Object.assign(config.params || {}, { timestamp: new Date().getTime() });
    }
    return config;
}, errorHandler);

// 响应拦截
service.interceptors.response.use((response) => {
    const res = response.data;

    if (res.code !== 200) {
        Notification({
            title: '提示',
            message: res.message || 'Error',
            type: 'error',
            duration: 3000
        });

        // 50008: 未登录
        if (res.code === 50008) {
            console.log('未登录');
        }
        return Promise.reject(new Error(res.message || 'Error'));
    } else {
        return res;
    }
}, errorHandler);

const installer = {
    vm: {},
    install (Vue) {
        Object.defineProperties(Vue.prototype, {
            $axios: {
                get() {
                    return service;
                }
            },
            $post: {
                get () {
                    return service.post;
                }
            }
        });
    }
};

export default service;

export {
    installer as VueAxios,
};
